Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

234
Vistas
Javascript | Validate structure of object based on custom schema

Working on a API that needs to validate the strucutre of the incoming request object. Based on other answers to similar questions, I have tried to create a solution that doesn't seem to be working.

My code so far:

 const testObj = {
            "uuid": {
                "value": "5481da7-8b7-22db-d326-b6a0a858ae2f",
                "type": "id"
            },
            "rate": {
                "value": 0.12,
                "type": "percent"
            }
        }

        let ok = true;

        ok = testObj === OBJECT_SCHEMA; // is false. Expected to be true

My validation schema:

const OBJECT_SCHEMA = {
    "uuid": {
        "value": String,
        "type": String
    },
    "rate": {
        "value": Number,
        "type": String
    }
}

Can aynone pinpoint what I'm doing wrong here?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

testObj === OBJECT_SCHEMA is returning false because the value of testObj and OBJECT_SCHEMA types are equal but not values.

My recommendation would be to checkout Yup or Zod for creating a validation

about 4 years ago · Juan Pablo Isaza Denunciar

0

Something to get you started:

let validate = (obj, schema) =>
    typeof obj === 'object'
        ? Object.keys(schema).every(k => validate(obj[k], schema[k]))
        : obj?.constructor === schema;

//

const OBJECT_SCHEMA = {
    "uuid": {
        "value": String,
        "type": String
    },
    "rate": {
        "value": Number,
        "type": String
    }
}


testObj = {
    "uuid": {
        "value": "5481da7-8b7-22db-d326-b6a0a858ae2f",
        "type": "id"
    },
    "rate": {
        "value": 0.12,
        "type": "percent"
    }
}

console.log(validate(testObj, OBJECT_SCHEMA))
testObj.rate.value = 'foo'
console.log(validate(testObj, OBJECT_SCHEMA))
delete testObj.rate.value
console.log(validate(testObj, OBJECT_SCHEMA))

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda